#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：图灵学习 
@File    ：10.进程池.py
@IDE     ：PyCharm 
@Author  ：ChenLiGao
@Date    ：2024-11-06 10:31
'''
import os
import random
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import Pool
import time


def work(message):
    p_start = time.time()
    print(f"{message}开始执行，任务的进程编号：{os.getpid()}")
    time.sleep(random.random() * 2)
    p_end = time.time()
    print(f"{message}执行完毕，耗时为：{p_end - p_start}")


if __name__ == '__main__':
    main_start = time.time()

    # 创建进程池对象
    pool = Pool(5)

    for item in range(1, 11):
        # # 同步传递
        # pool.apply(work, (item, ))
        # 并发调用
        pool.apply_async(work, (item, ))

    print("--------start--------------")
    pool.close() # 关闭进程池，关闭之后进程池对象不在接收新的任务，已有的任务会继续执行完
    pool.join() # 主进程等待进程池对象任务全部完成之后解堵塞，join必须在close方法之后调用

    main_end = time.time()
    print(f"主线程耗时：{main_end - main_start}")